import config from './chartConfig';
import { cloneDeep, assign } from 'lodash';
import { moment } from 'istrong-timeutil';
import Highcharts from 'istrong-highcharts';

let mergeOptions = (list, beginTime, endTime) => {
  let chartOpt = cloneDeep(config);

  let data = [];

  let minVal = list.length > 0 ? list[0].wind_speed : 0;
  let maxVal = list.length > 0 ? list[0].wind_speed : 50;

  let minTime = parseInt(moment(beginTime).format('x'), 10);
  let maxTime = parseInt(moment(endTime).format('x'), 10);

  list.forEach((item, i) => {
    let tm = parseInt(moment(item.time).format('x'), 10);
    data.push({
      x: tm,
      y: item.wind_speed
    });
    minVal = Math.min(minVal, item.wind_speed);
    maxVal = Math.max(maxVal, item.wind_speed);
  });

  var yInterval = (((maxVal + 1) - (minVal - 1)) / 6).toFixed(2);
  chartOpt = assign(chartOpt, {
    chart: {
      type: 'line',
      marginRight: 50,
      marginLeft: 50,
      marginTop: 30,
      marginBottom: 40,
      alignTicks: false
    },
    xAxis: {
      labels: {
        formatter: function () {
          return moment(this.value).format('HH时<br/>DD日')
        }
      },
      lineColor: '#808080',
      lineWidth: 0,
      tickColor: '#808080',
      tickWidth: 1,
      tickLength: 5,
      tickPosition: 'outside',
      gridLineWidth: 1,
      endOnTick: true,
      startOnTick: true,
      tickAmount: 8,
      min: minTime,
      max: maxTime,
      tickInterval: 1000 * 3600
    },
    yAxis: [
      {
        lineWidth: 1,
        lineColor: '#808080',
        gridLineDashStyle: 'longdash',
        gridLineColor: '#E0E0E0',
        tickInterval: yInterval,
        endOnTick: false,
        labels: {
          align: 'right',
          x: -3,
          y: 0,
          formatter: function () {
            return this.value.toFixed(2)
          }
        },
        title: {
          text: '风速(m/s)',
          align: 'high',
          rotation: 0,
          x: 60,
          y: -12
        },
        max: maxVal,
        min: minVal
      }
    ],
    series: [{
      data: data,
      color: '#5399d7'
    }]
  });
  return chartOpt;
}
let renderChart = (chartViewer, chartId, data, beginTime, endTime) => {
  if (chartViewer) {
    chartViewer.destroy();
  }
  let list = data.data || [];
  let chartOpt = mergeOptions(list, data.begin_time || beginTime, data.end_time || endTime);

  chartOpt.chart.renderTo = chartId;
  chartViewer = new Highcharts.Chart(chartOpt);
  return chartViewer;
};

export default renderChart;
